package vn.huync.smsbackupandrestore;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Calendar;

import vn.huync.smsbackupandrestore.models.SmsModel;
import vn.huync.smsbackupandrestore.others.Utils;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.nch.smsbackupandrestore.R;

public class RestoreActivity extends Activity {
	
	private static final int DIALOG_MORE_RESTORE_OPTION = 4;
	
	MyApp myApp;
	ListView listView;
	Button restoreButton;
	Button restoreOptionButton;
	String[] listFile;
	CheckBox selectAllCheckbox;
	
	// note: need reset isCheckedArray and numberChecked when setChecked for list item
	boolean[] isCheckedArray;			
	int numberChecked;
	
	ProgressDialog progressDialog;
	
	@SuppressLint("HandlerLeak")
	Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			int numSmsRestored = msg.getData().getInt("numSmsRestored");
			progressDialog.setProgress(numSmsRestored);
			if(progressDialog.getProgress() == progressDialog.getMax()){
				progressDialog.dismiss();
				Utils.ShowToast(RestoreActivity.this, 
						numSmsRestored + " " + getString(R.string.sms_has_been_restored));
			}
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_restore);
		
		listView = (ListView)findViewById(R.id.l_restore_file);
		restoreButton = (Button)findViewById(R.id.b_restore_now);
		restoreOptionButton = (Button)findViewById(R.id.b_restore_with_option);
		selectAllCheckbox = (CheckBox)findViewById(R.id.c_select_all);
		
		myApp = (MyApp)getApplicationContext();
		
		Thread loadFileThread = new Thread(new Runnable() {
			
			public void run() {
				File dir = new File(myApp.appFolderPath);
				listFile = dir.list(new FilenameFilter() {
					
					public boolean accept(File dir, String filename) {
						if(filename.endsWith(".xml"))
							return true;
						else return false;
					}
				});
				
				final RestoreAdapter adapter = new RestoreAdapter(getApplicationContext(), listFile);
				isCheckedArray = new boolean[listFile.length];
				
				runOnUiThread(new Runnable() {
					
					public void run() {
						listView.setAdapter(adapter);
					}
				});
				
			}
		});
		loadFileThread.start();
		
		restoreButton.setOnClickListener(onClickListener);
		restoreOptionButton.setOnClickListener(onClickListener);
		
		listView.setItemsCanFocus(true);
		
		selectAllCheckbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				int childCount = listView.getChildCount();
				for(int i = 0; i < childCount; i++){
					View row = listView.getChildAt(i);
					CheckBox checkbox = (CheckBox)row.findViewById(R.id.row_rt_checkbox);
					checkbox.setChecked(isChecked);
				}
			}
		});
		
		AdView adView = (AdView)this.findViewById(R.id.adView);
	    AdRequest.Builder adRequestBuilder = new AdRequest.Builder();
	    adRequestBuilder.addTestDevice("EEB3EC34691D85EFD1DF789EA3776326");
	    adRequestBuilder.addTestDevice(AdRequest.DEVICE_ID_EMULATOR);
	    AdRequest adRequest = adRequestBuilder.build();
	    adView.loadAd(adRequest);
	}
	
	protected android.app.Dialog onCreateDialog(int id) 
	{
		AlertDialog.Builder dialogBuilder;
		LayoutInflater factory = LayoutInflater.from(RestoreActivity.this);
		switch(id){
		case DIALOG_MORE_RESTORE_OPTION:
			final View vRestoreOption = factory.inflate(R.layout.restore_option, null);
			final DatePicker dpDateFrom = (DatePicker)vRestoreOption.findViewById(R.id.choose_date_from);
			final DatePicker dpDateTo = (DatePicker)vRestoreOption.findViewById(R.id.choose_date_to);
			
			dialogBuilder = new AlertDialog.Builder(RestoreActivity.this);
			dialogBuilder.setTitle(R.string.restore_option_title);
			dialogBuilder.setView(vRestoreOption);
			
			dialogBuilder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					
					Calendar c = Calendar.getInstance();
					c.set(Calendar.DAY_OF_MONTH, dpDateFrom.getDayOfMonth());
					c.set(Calendar.MONTH, dpDateFrom.getMonth());
					c.set(Calendar.YEAR, dpDateFrom.getYear());
					c.set(Calendar.HOUR_OF_DAY, 0);
					c.set(Calendar.MINUTE, 0);
					c.set(Calendar.SECOND, 0);
					
					final long from = c.getTimeInMillis();
					c.set(Calendar.DAY_OF_MONTH, dpDateTo.getDayOfMonth());
					c.set(Calendar.MONTH, dpDateTo.getMonth());
					c.set(Calendar.YEAR, dpDateTo.getYear());
					c.set(Calendar.HOUR_OF_DAY, 23);
					c.set(Calendar.MINUTE, 59);
					c.set(Calendar.SECOND, 59);
					
					final long to = c.getTimeInMillis();
					
					final ArrayList<SmsModel> lSmsAll = new ArrayList<SmsModel>();
					
					for(int i = 0; i < listFile.length; i++){
						if(isCheckedArray[i] == true){
							String fileName = listFile[i];
							ArrayList<SmsModel> lSms = Utils.ReadSmsFromSDCardToList( myApp.appFolderPath + fileName);
							SmsModel.addListToList(lSmsAll, lSms, from, to);
						}
					}
					SmsModel.deleteSmsExistInDbFromArray(getApplicationContext(), lSmsAll);
					if(lSmsAll.size() > 0){
						showProgressBar(lSmsAll.size());
						Thread restoreThread = new Thread(new Runnable() {
							
							public void run() {
								Utils.WriteSmsFromListToDb(RestoreActivity.this, lSmsAll, handler);
							}
						});
						restoreThread.start();
					}
					else{
						Utils.ShowToast(RestoreActivity.this, 
								0 + " " + getString(R.string.sms_has_been_restored));
					}
					
				}
			});
			
			dialogBuilder.setNegativeButton(android.R.string.cancel, null);
			
			return dialogBuilder.create();
		}
		return null;
	}

	View.OnClickListener onClickListener = new View.OnClickListener() {
		
		public void onClick(View v) {
			if(v.getId() == R.id.b_restore_now){
				
				final ArrayList<SmsModel> lSmsAll = new ArrayList<SmsModel>();
				
				if(numberChecked > 0){
					
					for(int i = 0; i < listFile.length; i++){
						if(isCheckedArray[i] == true){
							String fileName = listFile[i];
							ArrayList<SmsModel> lSms = Utils.ReadSmsFromSDCardToList( myApp.appFolderPath + fileName);
							SmsModel.addListToList(lSmsAll, lSms);
						}
					}
					
					SmsModel.deleteSmsExistInDbFromArray(getApplicationContext(), lSmsAll);
					if(lSmsAll.size() > 0){
						showProgressBar(lSmsAll.size());
						Thread restoreThread = new Thread(new Runnable() {
							
							public void run() {
								Utils.WriteSmsFromListToDb(RestoreActivity.this, lSmsAll, handler);
							}
						});
						restoreThread.start();
					}
					else{
						Utils.ShowToast(RestoreActivity.this, 
								0 + " " + getString(R.string.sms_has_been_restored));
					}
				}
				else Utils.ShowToast(RestoreActivity.this, R.string.please_select_file_to_restore);
			}
			else if(v.getId() == R.id.b_restore_with_option){
				if(numberChecked > 0)
					showDialog(DIALOG_MORE_RESTORE_OPTION);
				else Utils.ShowToast(RestoreActivity.this, R.string.please_select_file_to_restore);
			}
		}
	};
	
	void showProgressBar(int max){
		progressDialog = new ProgressDialog(this);
		progressDialog.setCancelable(false);
		progressDialog.setMessage(getString(R.string.restoring));
		progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		progressDialog.setProgress(0);
		progressDialog.setMax(max);
		progressDialog.show();
	}
	
	class RestoreAdapter extends ArrayAdapter<String>{
		Context context;
		String[] lFiles;
		RestoreAdapter adapter;
		
		public RestoreAdapter(Context context, String[] lFiles) {
			super(context, 0, lFiles);
			this.context = context;
			this.lFiles = lFiles;
			adapter = this;
		}
		
		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			View row = convertView;
			if(row == null){
				LayoutInflater inflater = LayoutInflater.from(RestoreActivity.this);
				row = inflater.inflate(R.layout.row_text_checkbox, null);
				
				ImageView iconImageView = (ImageView)row.findViewById(R.id.row_rt_icon);
				iconImageView.setImageResource(R.drawable.view_icon);
			}
			
			TextView tText = (TextView) row.findViewById(R.id.row_rt_text);
			CheckBox cCheck = (CheckBox)row.findViewById(R.id.row_rt_checkbox);
			
			row.setOnClickListener(new OnClickListener() {
				
				public void onClick(View v) {
					isCheckedArray[position] = !isCheckedArray[position];
					if(isCheckedArray[position]) {
						numberChecked++;
					}
					else {
						numberChecked--;
					}
					adapter.notifyDataSetChanged();
				}
			});
			
			String fileName = lFiles[position];
			tText.setText(fileName);
			
			cCheck.setChecked(isCheckedArray[position]);
			
			return row;
		}
	}

}
